(ns amsi.server.main
  (:require [amsi.server.server :as server])
  (:require [amsi.common.worker :as worker])
  (:require [amsi.common.logging :as logger])
  (:require [amsi.offer.offer :as offer]))

;Creates input queue
(def in-queue (ref (worker/create-queue)))

;Creates output queue
(def out-queue (ref (worker/create-queue)))

;Unique client's offers
(def unique-offers (ref {}))

;All client's offers
(def all-offers (ref {}))

(defn send-message-to-client
  "Send message to client."
  [task args]
  (let[ out (:out (:streams task)) message (:message task)]
    (logger/log "sends message to client" message)
    (.println out message)
    (.flush out)))

;Creates worker for sending messages to clients
(worker/start-workers out-queue 5 send-message-to-client {})
    
;Creates worker for processing user's input
(worker/start-workers in-queue 5 offer/process-request1 {:out-queue out-queue :unique-offers unique-offers :all-offers all-offers})

(defn message-in-queue
  "Reads input from socket and puts it in queue"
  [streams args]
    (let[input (.readLine (:in streams))]
      (logger/log "client sent" input)
      (if (nil? input)
        nil
        (do          
          (dosync 
            (.put @(:queue args) {:streams streams :offer input}))
          (recur streams args)))))
  
;Starts server
(server/listen 5432 message-in-queue {:queue in-queue })

